package com.gxks.lhs.controller.user;


import com.alibaba.druid.filter.logging.CommonsLogFilter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxks.lhs.DTO.OrderDetailDTO;
import com.gxks.lhs.DTO.PayDTO;
import com.gxks.lhs.DTO.UserFindOrder;
import com.gxks.lhs.constants.R;
import com.gxks.lhs.entity.AddressBook;
import com.gxks.lhs.entity.Goods;
import com.gxks.lhs.entity.Order;
import com.gxks.lhs.entity.User;
import com.gxks.lhs.security.SecurityUtils;
import com.gxks.lhs.service.*;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author LuoHaisong
 * @since 2023-06-02
 */
@Slf4j
@RestController
@RequestMapping("/restful-api/orders")
public class UserOrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAddressBookService addressBookService;
    @Autowired
    private IGoodsService goodsService;

    @ApiOperation("创建订单")
    @PostMapping("/create")
    public R createOrder(@RequestBody Order order) {
        if (order == null) {
            return R.error("订单信息不能为空");
        }
        String userId = SecurityUtils.getCurrentUserId();
        order.setBuyerId(userId);
        String orderId = orderService.createOrder(order);
        if (orderId != null) {
            return R.success(orderId, "订单创建成功");
        }
        return R.error("创建失败，请稍后重试");
    }


    @ApiOperation("用户查询订单列表")
    @GetMapping("/mySaleOrder")
    public R queryMySaleOrderList(UserFindOrder userFindOrder) {
        String userId = SecurityUtils.getCurrentUserId();
        Order queryOrder = new Order();
        queryOrder.setSellerId(userId);
        queryOrder.setStatus(userFindOrder.getOrderStatus());
        Page<Order> orderPage = orderService.findUserOrderList(queryOrder, userFindOrder.getCurrent());
        if (orderPage != null) {
            return R.success(orderPage);
        }
        return R.error();
    }

    @ApiOperation("用户查询订单列表")
    @GetMapping("/myBuyOrder")
    public R queryMyBuyOrderList(UserFindOrder userFindOrder) {
        String userId = SecurityUtils.getCurrentUserId();
        Order queryOrder = new Order();
        queryOrder.setBuyerId(userId);
        queryOrder.setStatus(userFindOrder.getOrderStatus());
        Page<Order> orderPage = orderService.findUserOrderList(queryOrder, userFindOrder.getCurrent());
        if (orderPage != null) {
            return R.success(orderPage);
        }
        return R.error();
    }

    @ApiOperation("根据订单id查询订单详细信息")
    @GetMapping("/query")
    public R queryOrderById(String orderId) {
        if (orderId == null) {
            return R.error("订单id不能为空");
        }
        String userId = SecurityUtils.getCurrentUserId();
        OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
        Order order = orderService.findOrderByIdOfUser(orderId, userId);
        if (order == null) {
            return R.error("订单不存在");
        }
        User user = userService.getById(order.getSellerId());
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());
        Goods goods = goodsService.getById(order.getProductId());
        orderDetailDTO.setSellerId(order.getSellerId());
        orderDetailDTO.setSellerName(user.getNickname());
        orderDetailDTO.setTotal(order.getTotalPrice());
        orderDetailDTO.setTotalNum(1);
        orderDetailDTO.setUserAddr(addressBook);
        orderDetailDTO.setGoods(goods);
        orderDetailDTO.setCreateTime(order.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss")));
        orderDetailDTO.setPayTime(order.getPayTime().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss")));
        orderDetailDTO.setPayName(order.getPayName());
        orderDetailDTO.setStatus(order.getStatus());
        return R.success(orderDetailDTO);
    }

    @ApiOperation("根据id取消订单")
    @PutMapping("/cancel/{orderId}")
    public R cancelOrderById(@PathVariable("orderId") String orderId) {
        String userId = SecurityUtils.getCurrentUserId();
        if (orderService.cancellationOfOrderByIdAndUserId(userId, orderId)) {
            return R.success().setMsg("订单取消成功");
        }
        return R.error("订单取消失败");
    }

    @ApiOperation("根据id对订单进行退款")
    @PutMapping("/refund")
    public R refundOrderById(@RequestBody Integer orderId) {
        if (orderService.refundOrderById(orderId)) {
            return R.success().setMsg("订单退欯后成功");
        }
        return R.error("订单退欯失败");
    }

    @ApiOperation("更新订单信息")
    @PostMapping("/update")
    public R updateOrder(@RequestBody Order order) {
        if (orderService.updateOrder(order)) {
            return R.success().setMsg("订单更新成功");
        }
        return R.error("订单更新失败");
    }

    /**
     * 支付订单
     */
    @ApiOperation("支付订单")
    @PostMapping("/pay")
    public R payOrder(@RequestBody PayDTO payDTO) {
        if (payDTO == null) {
            return R.error("支付信息不能为空");
        }
        if (payDTO.getPayType() == null) {
            return R.error("请选择支付方式");
        }
        String userId = SecurityUtils.getCurrentUserId();
        Boolean payStatus = false;
        log.info("订单支付，订单id{},选择的支付方式：{}", payDTO.getOrdersId(), payDTO.getPayType());
        // 根据支付方式支付
        //1、余额支付
        if (Objects.equals(payDTO.getPayType(), "balance")) {
            payStatus = orderService.balancePayOrder(userId, payDTO.getOrdersId());
        } else if (Objects.equals(payDTO.getPayType(), "alipay")) {
            return R.error("支付宝支付暂未开放");
        } else if (Objects.equals(payDTO.getPayType(), "wechat")) {
            return R.error("微信支付暂未开放");
        } else if (Objects.equals(payDTO.getPayType(), "testPay")) {
            payStatus = orderService.testPayOrder(userId, payDTO.getOrdersId());
        }
        //根据支付状态返回支付结果
        if (payStatus) {
            return R.success().setMsg("支付成功");
        } else {
            return R.error("支付失败");
        }
    }

    //订单确认收货
    @ApiOperation("确认收货")
    @PutMapping("/receipt/{orderId}")
    public R confirmOrder(@PathVariable("orderId") String orderId) {
        String userId = SecurityUtils.getCurrentUserId();
        if (orderService.receipt(userId, orderId)) {
            return R.success().setMsg("订单确认收货成功");
        }
        return R.error("订单确认收货失败");
    }

    @ApiOperation("订单发货")
    @PutMapping("/delivery")
    public R deliveryOrder(@RequestBody Map<String, String> expressNumber) {
        String userId = SecurityUtils.getCurrentUserId();
        Order order = new Order();
        order.setSellerId(userId);
        order.setId(expressNumber.get("orderId"));
        order.setLogisticsNum(expressNumber.get("expressNumber"));
        order.setStatus(3);
        if (orderService.updateOrder(order)) {
            return R.success().setMsg("订单发货成功");
        }
        return R.error("订单发货失败");
    }

    @ApiOperation("根据订单id获取订单支付信息")
    @GetMapping("/payInfo/{orderId}")
    public R getPayInfo(@PathVariable("orderId") String orderId) {
        Order order = orderService.getById(orderId);
        if (order == null) {
            return R.error("订单不存在");
        }
        if (order.getStatus() != 1) {
            return R.error("订单状态错误");
        }
        return R.success(order);
    }


}

